<template>
  <div class="orderRefund">
    <PageTitle title="申请退款"></PageTitle>
    <div class="wrap" v-if="orderDetail">
      <van-cell
        title="订单编号"
        :value="orderDetail.order_id"
        clickable
        @click="copyOrderId"
      />
      <van-cell title="下单时间" :value="orderDetail._add_time" />
      <van-cell title="订单状态" :value="orderDetail._status._title" />
      <van-collapse v-model="activeNames" class="cart">
        <van-collapse-item
          :title="`退款商品(${orderDetail.cartInfo.length})`"
          name="1"
        >
          <div class="cartList">
            <div
              class="card"
              v-for="item in orderDetail.cartInfo"
              :key="item.id"
              @click="$router.push('/detail/' + item.productInfo.id)"
            >
              <van-card
                :num="item.cart_num"
                :price="item.truePrice"
                :desc="item.productInfo.attrInfo.suk"
                :title="item.productInfo.store_name"
                :thumb="item.productInfo.image"
              />
            </div>
          </div>
        </van-collapse-item>
      </van-collapse>
      <van-cell title="退款金额" :value="`￥${orderDetail.pay_price}`" />
      <van-cell
        title="退款原因"
        :value="cause ? cause : '选择退款原因'"
        is-link
        @click="showCause = true"
      />
      <van-field
        v-model="explain"
        rows="2"
        autosize
        label="备注说明"
        type="textarea"
        maxlength="100"
        placeholder="填写备注信息"
        input-align="right"
        show-word-limit
      />
      <van-field
        name="uploader"
        label="文件上传"
        show-word-limit
        maxlength="3"
        :value="curImgNum"
      >
        <template #input>
          <van-uploader
            v-model="imgList"
            :after-read="uploadImg"
            :before-delete="deleteImg"
            :max-count="3"
          />
        </template>
      </van-field>
    </div>
    <div class="btn" v-if="orderDetail">
      <van-button round block color="#25c9c3" @click="submitRefund"
        >申请退款</van-button
      >
    </div>
    <van-action-sheet
      v-model="showCause"
      :actions="causeActions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelectCause"
    />
    <input
      type="text"
      class="copyOrderId"
      ref="copyOrderId"
      v-if="orderDetail"
      :value="orderDetail.order_id"
    />
  </div>
</template>

<script>
import PageTitle from "@/components/PageTitle";
import { mapMutations } from "vuex";
export default {
  name: "OrderRefund",
  data() {
    return {
      orderDetail: null,
      activeNames: ["1"],
      showCause: false,
      causeActions: [
        { name: "收货地址填错了" },
        { name: "与描述不符" },
        { name: "信息填错了，重新拍" },
        { name: "收到商品损坏了" },
        { name: "未按预定时间发货" },
        { name: "其它原因" },
      ],
      cause: "",
      explain: "",
      imgList: [],
    };
  },
  props: ["orderId"],
  components: {
    PageTitle,
  },
  computed: {
    curImgNum() {
      return " ".repeat(this.imgList.length);
    },
  },
  created() {
    this.getOrderDetail();
  },
  methods: {
    ...mapMutations(["changeLoading"]),
    getOrderDetail() {
      this.changeLoading(true);
      this.$axios.get(`/api/order/detail/${this.orderId}`).then((d) => {
        this.changeLoading(false);
        console.log("order/detail", d.data);
        if (d.data.status == 200) {
          this.orderDetail = d.data.data;
          if (this.orderDetail._status._type == -1) {
            this.$toast.fail("该订单已提交退款");
            this.$router.go(-1);
          } else if (this.orderDetail._status._type == 0) {
            this.$toast.fail("该订单还未付款");
            this.$router.go(-1);
          }
        } else if (d.data.status == 410000) {
          this.$toast.fail("请重新登录");
          this.$store.commit("loginOut");
          this.$router.push("/login");
        } else {
          this.$toast.fail(d.data.msg);
          if (window.history.length <= 1) {
            this.$router.push("/");
          } else {
            this.$router.go(-1);
          }
        }
      });
    },
    onSelectCause(item) {
      this.cause = item.name;
    },
    copyOrderId() {
      let input = this.$refs["copyOrderId"];
      input.select();
      input.setSelectionRange(0, 9999);
      if (document.execCommand("Copy")) {
        this.$toast("订单编号已复制");
      }
    },
    uploadImg(img) {
      let file = img.file;
      if (file.type.indexOf("image") == 0) {
        let param = new FormData();
        param.append("file", file);
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "上传中...",
        });
        img.status = "uploading";
        img.message = "上传中...";
        this.$axios
          .post("/api/upload/image", param, {
            headers: { "Content-Type": "multipart/form-data" },
          })
          .then((d) => {
            console.log("upload/image", d.data);
            this.$toast.clear();
            if (d.data.status == 200) {
              img.status = "done";
              img.url = d.data.data.url;
            } else {
              this.$toast.fail(d.data.msg);
              img.status = "failed";
              img.message = "上传失败";
              this.deleteImg(img);
            }
          });
      }
    },
    deleteImg(img) {
      this.imgList = this.imgList.filter((i) => i != img);
    },
    submitRefund() {
      if (!this.cause) {
        this.$toast("请选择退款原因");
        return;
      }
      let img = this.imgList
        .filter((i) => i.url)
        .map((i) => i.url)
        .join(",");
      let params = {
        uni: this.orderDetail.order_id,
        text: this.cause,
        refund_reason_wap_img: img,
        refund_reason_wap_explain: this.explain,
      };
      //   console.log(params);
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "请求中...",
      });
      this.$axios.post("/api/order/refund/verify", params).then((d) => {
        console.log("order/refund/verify", d.data);
        this.$toast.clear();
        if (d.data.status == 200) {
          this.$toast.success("提交退款成功");
          this.$router.push("/order/list/5");
        } else if (d.data.status == 410000) {
          this.$toast.fail("请重新登录");
          this.$store.commit("loginOut");
          this.$router.push("/login");
        } else {
          this.$toast.fail(d.data.msg);
          this.$router.go(-1);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.orderRefund {
  .wrap {
    margin-top: 15px;
    .cart {
      &::after {
        border: none;
      }
      .van-collapse-item {
        position: relative;
        &::after {
          content: "";
          position: absolute;
          pointer-events: none;
          right: 16px;
          bottom: 0;
          left: 16px;
          border-bottom: 1px solid #ebedf0;
          -webkit-transform: scaleY(0.5);
          transform: scaleY(0.5);
        }
        ::v-deep .van-collapse-item__content {
          padding-top: 0;
          padding-bottom: 0;
        }
        .cartList {
          .card {
            padding: 0 10px;
            background: #fff;
            &:active {
              background: #f2f3f5;
            }
            &:not(:first-child) .van-card {
              border-top: 1px solid #f5f5f5;
            }
            .van-card {
              padding: 15px 0;
              background: inherit;
              .van-card__thumb {
                height: 75px;
                width: 75px;
              }
              .van-card__content {
                min-height: 75px;
              }
            }
          }
        }
      }
    }
  }
  .copyOrderId {
    position: fixed;
    top: -9999px;
    left: -9999px;
    opacity: 0;
  }
  .btn {
    margin: 25px 16px;
  }
}
</style>